package com.diqye.db.manage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.sql.DataSource;

import com.diqye.db.XConf;
import com.diqye.db.Tinfo;
import com.diqye.db.XDB;
import com.diqye.db.dialect.IDialect;
import com.diqye.db.event.TableEvent;
import com.diqye.db.exception.XException;

public class XManage {
	@SuppressWarnings("rawtypes")
	private static HashMap<Class, DataSource> datasourceentry = new HashMap<Class, DataSource>();
	@SuppressWarnings("rawtypes")
	private static HashMap<Class, IDialect> dialectentry = new HashMap<Class, IDialect>();
	@SuppressWarnings("rawtypes")
	private static HashMap<Class, List<TableEvent>> tableEventMap = new HashMap<Class, List<TableEvent>>();
	@SuppressWarnings("rawtypes")
	private static HashMap<Class, Tinfo> tinfoinsMap = new HashMap<Class, Tinfo>();  
	public static void putDatasource(Class<? extends Tinfo> tinfoclass,DataSource datasource){
		datasourceentry.put(tinfoclass, datasource);
	}
	
	public static void putDialect(Class<? extends Tinfo> tinfoclass,IDialect dialect){
		dialectentry.put(tinfoclass, dialect);
	}
	
	public static DataSource getDatasource(Class<? extends Tinfo> tinfoclass){
		DataSource ds=datasourceentry.get(tinfoclass);
		if(ds == null){
			ds = XConf.defaultDataSource;
		}
		return ds;
	}
	

	
	public static IDialect getDialect(Class<? extends Tinfo> tinfoclass){
		IDialect r=dialectentry.get(tinfoclass);
		if(r == null){
			r = XConf.defaultDialect;
		}
		return r;
	}
	
	public static List<TableEvent> getTableEvents(Class<? extends Tinfo> tinfoclass){
		return  tableEventMap.get(tinfoclass);
	}
	
	public static void addTableEvent(Class<? extends Tinfo> tinfoclass, TableEvent tableevent){
		List<TableEvent> r = tableEventMap.get(tinfoclass);
		if(r == null){
			r = new ArrayList<TableEvent>();
			tableEventMap.put(tinfoclass, r);
		}
		r.add(tableevent);
	}
	
	public static Tinfo getTinfo(Class<? extends Tinfo> tinfoclass){
		Tinfo r =  tinfoinsMap.get(tinfoclass);
		if(r == null){
			buildTinfo(tinfoclass);
			r =  tinfoinsMap.get(tinfoclass);
		}
		
		return r;
	}
	
	public static void buildTinfo(Class<? extends Tinfo> tinfoclass){
		XDB db = new XDB(getDatasource(tinfoclass));
		try {
			Tinfo tinfo = tinfoclass.newInstance();
			String sql = getDialect(tinfoclass).tableInfosql(tinfo.getTablename());
			List<String> fields = db.jdbcFields(sql, null);
			for(String field : fields){
				tinfo.addField(field);
			}
			tinfoinsMap.put(tinfoclass, tinfo);
		} catch (InstantiationException e) {
			new XException("",e);
		} catch (IllegalAccessException e) {
			new XException("",e);
		}
	}
	
	
}
